package uit.mmt02.activity;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import uit.mmt02.R;
import uit.mmt02.xuly.ConvertMessageToList;
import uit.mmt02.dataAccess.DB_EmailLoginManager_Adapter;
import uit.mmt02.dataAccess.db_email;
import uit.mmt02.doituong.OneMail;
import uit.mmt02.adapter.myadapter;
import uit.mmt02.doituong.showToast;
import uit.mmt02.mailControl.YahooControl;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class getYahooActivity extends Activity
{
	final static String tag   = "getYAHOOactivity";
	YahooControl g ;
	
	//---------------------------------Copy...
	
	final static String KEY_USERNAME_LOGIN = "USERNAMELOGIN"; // nhan USERVA PASS tu showmail activity gui toi de login
	final static String KEY_PASSWORD_LOGIN = "PASSWORDLOGIN";
	static final String FROM = "from";
	static final String BODY = "body";
	static final String SUB = "sub";
	static final String DATE = "date";
	static final String TIME = "time";
	static final String TO = "to";
	//option......................
	static final String ATTACH = "attach";
	static final String VOICE = "voice";
	static final String ENCRYPT = "encrypt";
	String username;
	String password;
	ArrayAdapter<OneMail>adapter;
	Message[]message;
	showToast d;
	List<OneMail>list; //list truyen vao adapter
	int n ; // so mail
	Bundle bundle; //nhan username va password
	ListView listview; //lay listview
	View view; // view footer
	LayoutInflater Linflater;
	Button btn_more, btn_logout;
	
	//
	
	db_email mydb;
	Cursor mCursor;
	int count_mail = 0;
	int count_limited = 5;
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_email_login);
		listview = (ListView)findViewById(R.id.listview_list_email);
		d = new showToast(getBaseContext());
		list = new ArrayList<OneMail>();	
		//
		Linflater = getLayoutInflater();
		view = Linflater.inflate(R.layout.footer_list_mail, null);
		//
		bundle = getIntent().getExtras();
		username = bundle.getString(KEY_USERNAME_LOGIN);
		password = bundle.getString(KEY_PASSWORD_LOGIN);
		Log.v(tag, "Nhan duoc : " + username + " | " + password);
		//goi class loadmail chay nhu 1 tien trinh moi
		new load_Yahoo_Mail().execute(tag);
		//-------------
		btn_more = (Button)view.findViewById(R.id.btn_foot_more);
		
		btn_more.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
//				final ProgressDialog pdialog1 = new ProgressDialog(getYahooActivity.this);
//				pdialog1.setMessage("Ä�ang táº£i ....");
//				pdialog1.show();
				d.showmess("mor mire");
				add_more_mail_to_list();
//				new load_more_mail().execute("more");
//				add_more_email();
//				pdialog1.dismiss();
//				new Runnable() {
//					public void run() {
//						add_more_email();
//						adapter.notifyDataSetChanged();
//						pdialog1.dismiss();
//					}
//				}.run();
//				adapter.notifyDataSetChanged();
//				new Thread(new Runnable() {
//					
//					@Override
//					public void run() {
//						// TODO Auto-generated method stub
//						add_more_email();
//						adapter.notifyDataSetChanged();
//						pdialog1.dismiss();
//						
//					}
//				}).start();
			}
		});
		
		btn_logout = (Button)view.findViewById(R.id.btn_foot_logout);
		btn_logout.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO REMOVE USERNAME NAY RA KHOI CSDL
				d.showmess("logout ...");
				DB_EmailLoginManager_Adapter mydb = new DB_EmailLoginManager_Adapter(getYahooActivity.this);
				mydb.open();
				mydb.remove_by_username(username);
				mydb.close();
				startActivity(new Intent(getYahooActivity.this,  uit.mmt02.activity.ListMailActivity.class));
				
			}
		});
		
		TextView txt_email = (TextView)view.findViewById(R.id.txt_foot_email);
		txt_email.setText(username);
	}
	
	// asyncTask Load mail
		private class load_Yahoo_Mail extends AsyncTask<String,String	, Message[]>
		{
			ProgressDialog pdialog = new ProgressDialog(getYahooActivity.this);
			
			@Override
			protected void onPreExecute() 
			{
//				pdialog.setTitle("Get Mail");
				pdialog.setMessage("Ä�ang táº£i email tá»« : " + username);
				pdialog.show();
				super.onPreExecute();
			}

			@Override
			protected Message[] doInBackground(String... params) 
			{
				// TODO Auto-generated method stub
//				Log.v(tag, "doinBackGroud");
//				g = new YahooControl(username, password);
//				message = g.getmail();
//				ConvertMessageToList cv = new ConvertMessageToList();
//				list = cv.convert2(message);
//				adapter = new myadapter(getYahooActivity.this, list);
////				LayoutInflater inflater = getLayoutInflater();
////				view = inflater.inflate(R.layout.footer_list_mail, null);
//				Log.v(tag, "end doinBackGroud");
//				return message;
				doinbackGround();
				return null;
				
			}
			@Override
			protected void onPostExecute(Message[] resultMes) {
				// TODO Auto-generated method stub
				Log.v(tag,"on post");
				
				listview.addFooterView(view);
				listview.setAdapter(adapter);
				pdialog.dismiss();
				super.onPostExecute(resultMes);
			}
			
		}
		
		
		//menu
		// tao menu 
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// TODO Auto-generated method stub
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.layout_menu, menu);
			return super.onCreateOptionsMenu(menu);
		}
		//khi click vao menu item
		@Override
		public boolean onOptionsItemSelected(MenuItem item) 
		{
			// TODO Auto-generated method stub
			switch (item.getItemId()) 
			{
				case R.id.item_layout_refresh:
					d.showmess("refresh");
					break;
				case R.id.item_layout_compose:
					d.showmess("new mail");
					Intent i = new Intent("uit.mmt02.activity.newmailActivity");
					startActivity(i);
					break;
				case R.id.item_layout_search:
					d.showmess("serach");
					break;
				case R.id.item_layout_markAll:
					d.showmess("selected all");
					break;
				case R.id.item_layout_unMark:
					d.showmess("un mark");
					break;
				case R.id.item_layout_delete:
					d.showmess("delete ...");
					break;
				default:
					break;
			}
			return super.onOptionsItemSelected(item);
		}
		
		//ham add them 5 email vao list
		@SuppressWarnings("unused")
		private void add_more_email() {
			// TODO Auto-generated method stub
			try
			{
				n = list.size(); // so mail da dc load
				int n_tongmail = message.length; // tong so mail
				int n_batdautai = n_tongmail -n-1;
				Log.v(tag, "get dc " + n_tongmail + "get tu " + n_batdautai);
				ConvertMessageToList cv2 = new ConvertMessageToList();
//				for (int i = 10 ; i > 5 ; i--)
				for (int i = n_batdautai ; i > n_batdautai-5 ; i--)
				{
					if(i >= 0)
					{
						OneMail om = cv2.get1mail(message, i);
						adapter.add(om);
						Log.v(tag, "get dc " + i);
					}
					
				}
//				adapter.notifyDataSetChanged();
			}
			
			catch (Exception e) {
				// TODO: handle exception
				Log.i(tag, "Loi add 5 email" + e.toString());
			}

		}
		
		//tao 1 tien trinh load them email rieng, 1 dialog bao ng dung doi
		@SuppressWarnings("unused")
		private class load_more_mail extends AsyncTask<String, String, String>
		{
			ProgressDialog pdialog = new ProgressDialog(getYahooActivity.this);
			
			@Override
			protected void onPreExecute() 
			{
//				pdialog.setTitle("Get Mail");
				pdialog.setMessage("Ä�ang táº£i ....");
				pdialog.show();
				super.onPreExecute();
			}

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
			
			// lay 5 mail tu csdl cho vao list
				
				return null;
			}
			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
//				adapter.notifyDataSetChanged();
				pdialog.dismiss();
				super.onPostExecute(result);
				
			}
			
		}
		
		public void doinbackGround()
		{
			// kiem tra CSDL cua user
			try
			{
			Log.v(tag, "doinBackGroud");
			g = new YahooControl(username, password);
			String []str = username.split("@");
			String db_name = "db_" + str[0] +"_yahoo";
			mydb = new db_email(getYahooActivity.this, db_name);
			mydb.open();
			mCursor = mydb.query();
			Log.v(tag, "GGGGGGGGGG");
			if(mCursor.getCount() == 0)
			{
				Log.v(tag, "GGGGGGGGGGhhhhhhhh");
				mCursor.close();
//				mydb.close();
				message = g.getmail();
//				g.save_mail_to_db(message);
//				Log.v(tag, "IFFFFFF--save email... update cursor");
//				
//				mydb.open();
//				mCursor = mydb.query();
				
				mydb.save_msg_to_db(message);
				mCursor = mydb.query();
			}
			Log.v(tag, "111111111111111111111111 : " +mCursor.getColumnCount()+ ".."+mCursor.getCount());
			if(mCursor.moveToFirst())
			{
				
				do
				{
					count_mail ++;
					int id = mCursor.getInt(0);
					String from = mCursor.getString(1);
					String to = mCursor.getString(2);
					String Sub = mCursor.getString(3);
					String body = mCursor.getString(4);
					String time = mCursor.getString(5);
					String attach = mCursor.getString(6);
					int flag_favorite = mCursor.getInt(7);
					int flag_encrypt = mCursor.getInt(8);
					int flag_voice = mCursor.getInt(9);
					boolean f_fa = (flag_favorite == 1 ? true:false);
					boolean f_en = (flag_encrypt ==1 ? true:false);
					boolean f_voi = (flag_voice==1?true:false);
					OneMail om3 = new OneMail(id, from, to, Sub, body, time, attach, f_fa,f_en,f_voi);
					list.add(om3);
					mCursor.moveToNext();
					
				}while(count_mail < count_limited);
			}
			count_limited += 5;
			adapter = new myadapter(getYahooActivity.this, list);
			mCursor.close();
			mydb.close();
			}catch (Exception e) {
				// TODO: handle exception
				Log.v(tag, "loi do in back");
			}
		}
		
		public void add_more_mail_to_list()
		{
			mydb.open();
			mCursor = mydb.query();
			Log.v(tag, "query back groung OK");
			if(mCursor.moveToFirst() && mCursor.getCount() >= count_limited)
			{
				do
				{
					
					mCursor.moveToPosition(count_mail);
					count_mail ++;
					int id = mCursor.getInt(0);
					String from = mCursor.getString(1);
					String to = mCursor.getString(2);
					String Sub = mCursor.getString(3);
					String body = mCursor.getString(4);
					String time = mCursor.getString(5);
					String attach = mCursor.getString(6);
					int flag_favorite = mCursor.getInt(7);
					int flag_encrypt = mCursor.getInt(8);
					int flag_voice = mCursor.getInt(9);
					boolean f_fa = (flag_favorite == 1 ? true:false);
					boolean f_en = (flag_encrypt ==1 ? true:false);
					boolean f_voi = (flag_voice==1?true:false);
					OneMail om3 = new OneMail(id, from, to, Sub, body, time, attach, f_fa,f_en,f_voi);
//					list.add(om3);
					adapter.add(om3);
//					mCursor.moveToNext();
					
				}while(count_mail < count_limited);
//				}while(mCursor.moveToNext());
				count_limited +=5;
			}else
			{
				d.showmess("tiep tuc get mail tu server online...");
			}
			
			mCursor.close();
			mydb.close();
			adapter.notifyDataSetChanged();
			
		}

}
